#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import sys
default_encoding = 'utf-8'
if sys.getdefaultencoding() != default_encoding:
    reload(sys)
    sys.setdefaultencoding(default_encoding)

import MySQLdb

# MySQL Info
DATABASE_NAME = 'plosp'
HOST = '10.188.188.22'
PORT = '3306'
USER_NAME = 'plosp'
PASSWORD = 'plosp'
CHAR_SET = 'utf8'
conn = MySQLdb.connect(host=HOST, user=USER_NAME, passwd=PASSWORD, db=DATABASE_NAME, charset=CHAR_SET)

infile=open("D:/pmid.txt","r")
outfile=open("D:/pmid_info.txt","w")
for line in infile:
    line=line.rstrip("\n")
    cursor=conn.cursor()
    sql="SELECT pmid,journal_id,year,volume,issue,page,title,author FROM tb_dds_article where pmid="+line
    cursor.execute(sql)
    result=cursor.fetchone()
    pmid=result[0]
    journal_id=result[1]
    year=result[2]
    if year==None:
        year=""
    volume=result[3]
    if volume==None:
        volume=""
    issue=result[4]
    if issue==None:
        issue=""
    page=result[5]
    if page==None:
        page=""
    title=result[6]
    author=result[7]
    author=str(author).replace("; ",", ")
    author=author.strip()
    if author.endswith(","):
        author=author[:-1]
    cursor2=conn.cursor()
    sql2="SELECT title FROM tb_dds_journal where id="+str(journal_id)
    cursor2.execute(sql2)
    result2=cursor2.fetchone()
    journal=result2[0]
    cursor2.close()
    cursor.close()
    source=journal
    if volume!="":
        source+=" "+volume
    if issue!="":
        source+="("+issue+")"
    if page!="":
        source+=";"+page
    outfile.write(str(pmid)+"\t"+source+"\t"+title+"\t"+str(year)+"\t"+author+"\n")
    outfile.flush()
outfile.close()
infile.close()
conn.close()
